<?php

namespace app\convert\controller;

/**
 * 通用文件处理
 */
class Index
{

    protected $config;

    public function __construct()
    {
        $this->config = config('file');
        $this->music  = db('music');
        $this->filedb = db('file');
    }

    /**
     * 批量文件检测
     */
    public function file()
    {
        //每次批量更新数
        $step_num = 100;
        $count    = $this->filedb->count();
        echo 'Total:' . $count . "\n";
        if ($count != 0) {
            for ($i = 0; $i <= $count; $i = $i + $step_num) {
                $list = $this->filedb->field('id,path')->limit($i . ',' . $step_num)->select();
                $this->_build_file($list);
                echo $i . " ok\n";
                flush();
                ob_flush();
            }
        }
        if ($count > 0) {
            sleep(2);
        }
    }

    private function _build_file($list = [])
    {
        if (empty($list) || !is_array($list)) {
            return;
        }

        //整理需要索引的数据
        foreach ($list as $v) {
            $path = $this->config['new_path'] . $v['path'];
            if (file_exists($path)) {
                $getid3 = getid3($path); //分析文件
                $this->filedb->where('id', $v['id'])->update(['mime' => $getid3['mime_type'], 'playtime' => $getid3['playtime_string']]); //更新
            }
        }
    }

    /**
     * 批量文件转换
     */
    public function index()
    {
        //每次批量更新数
        $step_num = 100;
//        $condition['id'] = 33;
        $condition['video'] = ['like', '%/music/%'];
//        $count = $this->music->where($condition)->count();
        $list = $this->music->field('id,video')->where($condition)->select();
        echo 'Total:' . count($list) . "\n";

        foreach ($list as $key => $value) {
            $this->_build_music($value);
            echo $key . " ok\n";
            sleep(2);
        }

//        if ($count > 0) {
        //            sleep(2);
        //        }
    }

    private function _build_music($list = [])
    {
        if (empty($list) || !is_array($list)) {
            return;
        }

        //整理需要索引的数据

        $path = $this->config['old_path'] . $list['video'];
        if (file_exists($path)) {
            $this->update($path, $list['id']);
        } else {
            echo $path . '不存在\n';
        }

    }

    /**
     * 文件处理
     * @param string  $file 文件路径
     * @param string  $id 文件id
     *
     */
    public function update($file, $id)
    {
        $filename = call_user_func('uniqid');
        $hash     = hash_file('sha1', $file);
        $getid3   = getid3($file); //分析文件
        $path     = $this->config['path'] . DS . date("Ymd");
        mkdirs($this->config['new_path'] . $path); //创建目录
        $paths     = $path . DS . $filename . '.' . $getid3['fileformat'];
        $new_paths = $this->config['new_path'] . $paths; //组成完整根路径
        $info      = $this->filedb->where('sha1', $hash)->find();
        if (empty($info)) {
            $copy = $this->recurse_copy($file, $new_paths); //拷贝文件
            if ($copy) {
                $this->music->where('id', $id)->update(['video' => $hash, 'playtime' => $getid3['playtime_string']]); //更新
                $info = [
                    'path'        => $paths,
                    'create_time' => time(),
                    'sha1'        => $hash,
                    'size'        => $getid3['filesize'],
                    'mime'        => $getid3['mime_type'],
                    'ext'         => $getid3['fileformat'],
                    'playtime'    => $getid3['playtime_string'],
                ];
                $this->filedb->insert($info); //新增
                //压缩mp3
                $temp_path = $this->config['temp_path'] . DS . substr($hash, 0, 2);
                mkdirs($temp_path); //创建目录
                $temp_paths = $temp_path . DS . '128_' . $hash . '.' . $getid3['fileformat']; //压缩输出完整根路径
                ffmpeg($new_paths, $temp_paths); //压缩mp3
            }
        } else {
            $this->music->where('id', $id)->update(['video' => $hash, 'playtime' => $getid3['playtime_string']]); //更新
        }
    }

    /**
     * 拷贝文件
     * @param  string $file 旧文件路径
     * @param  string $newfile 新文件路径
     * @return boolean  状态，true-成功，false-失败
     */
    public function recurse_copy($file, $newfile)
    {
        if (file_exists($file) == false) {
            return false; //文件不在,无法复制
        }
        $result = copy($file, $newfile);
        echo 'copy:' . $file . '==>' . $newfile;
        if ($result == true) {
            return true;
        } else {
            return false;
        }
    }
}
